package com.middlegroup.pay.web.api;

import com.alibaba.druid.util.StringUtils;
import com.middlegroup.common.enums.AlikeyEnums;
import com.middlegroup.common.enums.ChannelCode;
import com.middlegroup.common.enums.ConfigKeyEnums;
import com.middlegroup.common.enums.PaypalResponseCode;
import com.middlegroup.common.enums.ServiceType;
import com.middlegroup.common.model.PayRequest;
import com.middlegroup.common.model.QueryRequest;
import com.middlegroup.common.model.ResponseEntity;
import com.middlegroup.common.model.TransResult;
import com.middlegroup.common.utils.DateUtils;
import com.middlegroup.pay.bind.SessionMerchantCode;
import com.middlegroup.pay.dto.AliReturnQueryOrderResponse;
import com.middlegroup.pay.entity.InBills;
import com.middlegroup.pay.entity.RefundBills;
import com.middlegroup.pay.mapper.InBillsMapper;
import com.middlegroup.pay.mapper.RefundBillsMapper;
import com.middlegroup.pay.service.AlipayService;
import com.middlegroup.pay.service.PaypalService;
import com.middlegroup.pay.service.QueryService;
import com.middlegroup.pay.service.SystemCfgService;
import com.middlegroup.pay.service.WechatPayH5Service;
import com.paypal.api.payments.Payment;
import com.paypal.api.payments.Refund;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 *订单查询
 * @author pc
 * @date 2019/1/25
 */
@RestController
public class QueryController extends BaseController {

    @Resource
    private QueryService queryService;
    @Resource
    private InBillsMapper inBillsMapper;
    @Resource
    private RefundBillsMapper refundBillsMapper;
    @Autowired
    private PaypalService paypalService;
    @Autowired
    private AlipayService alipayService;
    @Autowired
    private WechatPayH5Service wechatPayH5Service;
    @Resource
    private SystemCfgService systemCfgService;

    /**订单查询
     * @param
     * @return
     */
    @RequestMapping("orderQuery")
    ResponseEntity orderQuery(@Valid QueryRequest request, @SessionMerchantCode String merchantCode){
        request.setMerchantCode(merchantCode);
        TransResult transResult = queryService.orderQuery(request);
        return new ResponseEntity(ResponseEntity.STATUS_OK,transResult);
    }

    /**新支付中台订单查询（支付宝 微信 贝宝）
     curl -i 'http://172.21.231.137:9090/payQuery?billNo=b6b40fa0cf2749cf9a65dfd2dd1e949c&merchantBillNo=WCHANT201908161801000002'
     */
    @RequestMapping("payQuery")
    ResponseEntity payQuery(@Valid String merchantBillNo, @Valid String billNo){
        if(StringUtils.isEmpty(merchantBillNo) && StringUtils.isEmpty(billNo)){
            return new ResponseEntity(ResponseEntity.STATUS_FAIL,"订单号和流水号不能同时为空");
        }
        InBills model = new InBills();
        model.setBillNo(billNo);
        model.setMerchantBillNo(merchantBillNo);
        InBills inBills = inBillsMapper.selectOne(model);
        if(inBills==null){
            return new ResponseEntity(ResponseEntity.STATUS_FAIL,"查询的支付数据不存在，请确认退款单号是否正确");
        }
        if(inBills.getStatus().intValue()!=1){
            switch (inBills.getServiceType()) {
                case wx_h5:
                    try{
                        //TODO 微信H5查询
                        PayRequest payRequest = new PayRequest();
                        payRequest.setMerchantCode(inBills.getMerchantCode());
                        payRequest.setSubjectCode(inBills.getSubjectCode());
                        payRequest.setMerchantBillNo(inBills.getMerchantBillNo());
                        payRequest.setBillNo(inBills.getBillNo());
                        wechatPayH5Service.wechatPayH5Query(payRequest);
                    }catch (Exception e){
                        logger.error("wx_h5第三方通道微信H5支付查询接口调用失败"+merchantBillNo,e);
                    }
                    break;
                case alipay_h5:
                    try{
                        //TODO 支付宝H5支付
                        AliReturnQueryOrderResponse aliReturnQueryOrderResponse = alipayService.AlipayQuery(merchantBillNo, billNo);
                        if(aliReturnQueryOrderResponse != null && AlikeyEnums.SUCCESS.name().equals(aliReturnQueryOrderResponse.getAlipay_trade_query_response().getCode())){
                            inBills.setStatus(1);
                           
                        }else if(aliReturnQueryOrderResponse != null && AlikeyEnums.NO_TRANS.getCode().equals(aliReturnQueryOrderResponse.getAlipay_trade_query_response().getCode()) 
                        		&& (null == aliReturnQueryOrderResponse.getAlipay_trade_query_response().getTrade_status() || "null".equals(aliReturnQueryOrderResponse.getAlipay_trade_query_response().getTrade_status()) )){

                        	/**
                        	 * 支付有效期内推迟2分钟，不返回支付失败
                        	 */
                            String timeout_express = systemCfgService.getConfigString("alipay_h5",ConfigKeyEnums.TIMEOUT_EXPRESS.getName());
                            Long timeout_trans = Long.parseLong(timeout_express.replace("m", ""));
                        	if (System.currentTimeMillis()-inBills.getAddTime() > (timeout_trans+2)*60*1000) {
                        		inBills.setStatus(2); 
							}
                        }
                        inBills.setOrderId(null == aliReturnQueryOrderResponse.getAlipay_trade_query_response().getTrade_no() ? "" : aliReturnQueryOrderResponse.getAlipay_trade_query_response().getTrade_no());
                        inBills.setUpdateTime(System.currentTimeMillis());
                        inBillsMapper.updateById(inBills);
                    }catch (Exception e){
                        logger.error("alipay_h5第三方通道支付宝H5支付查询接口调用失败"+merchantBillNo,e);
                    }
                    break;
                case paypal:
                    try {
                        Payment payment = paypalService.queryPay(inBills.getOrderId());
                        inBills.setStatus(PaypalResponseCode.getStatus(payment.getState()));
                        inBills.setUpdateTime(System.currentTimeMillis());
                        inBillsMapper.updateById(inBills);
                    } catch (Exception e) {
                        logger.error("paypal第三方通道微信H5支付查询接口调用失败"+merchantBillNo,e);
                    }
            }
        }
        return new ResponseEntity(ResponseEntity.STATUS_OK,inBills);
    }
    

    /**新支付中台退款订单查询（支付宝 微信 贝宝）
     curl -i 'http://172.21.231.137:9090/refundQuery?merchantBillNo=WCHAT201908191213000001&merchantRefundNo=REFUNDWCHANT2019081618010000062'
     */
    @RequestMapping("refundQuery")
    ResponseEntity refundQuery(@Valid String merchantBillNo, @Valid String billNo,@Valid String merchantRefundNo){
        if(StringUtils.isEmpty(merchantBillNo) && StringUtils.isEmpty(billNo)){
            return new ResponseEntity(ResponseEntity.STATUS_FAIL,"订单号和流水号不能同时为空");
        }
        if(StringUtils.isEmpty(merchantRefundNo) ){
            return new ResponseEntity(ResponseEntity.STATUS_FAIL,"退款单号不能为空");
        }
        RefundBills model = new RefundBills();
        model.setMerchantRefundNo(merchantRefundNo);//请求退款接口时，传入的退款请求号
        model.setRefundNo(billNo);//支付中心流水号
        model.setMerchantBillNo(merchantBillNo);//商家订单号
        RefundBills refundBills = refundBillsMapper.getRefundBills(model);
        if(refundBills==null){
            return new ResponseEntity(ResponseEntity.STATUS_FAIL,"查询的退款数据不存在，请确认退款单号是否正确");
        }
        if (refundBills.getStatus().intValue() != 1) {
            switch (ServiceType.valueOf(refundBills.getServiceType())) {
                case wx_h5:
                    try{
                        //TODO 微信H5退款查询
                        wechatPayH5Service.wechatPayH5RefundQuery(refundBills.getMerchantBillNo());
                    }catch (Exception e){
                        logger.error("wx_h5第三方通道微信H5退款查询接口调用失败"+merchantRefundNo,e);
                    }
                    break;
                case alipay_h5:
                    try{
                        //TODO 支付宝H5支付
                        AliReturnQueryOrderResponse aliReturnQueryOrderResponse = alipayService.refundQueryAlipay(refundBills.getOutRequestNo());
                        if(aliReturnQueryOrderResponse != null && AlikeyEnums.SUCCESS.name().equals(aliReturnQueryOrderResponse.getAlipay_trade_query_response().getCode())){
                            refundBills.setOutRequestNo(aliReturnQueryOrderResponse.getAlipay_trade_query_response().getTrade_no());
                            refundBills.setRefundTime(DateUtils.convert(aliReturnQueryOrderResponse.getAlipay_trade_query_response().getSend_pay_date()).getTime());
                            refundBills.setStatus(1);
                        }
                        refundBillsMapper.updateById(refundBills);
                    }catch (Exception e){
                        logger.error("alipay_h5第三方通道支付宝H5退款查询接口调用失败"+merchantRefundNo,e);
                    }
                    break;
                case paypal:
                    try {
                        Refund refund = paypalService.queryRefund(refundBills.getOutRequestNo());
                        refundBills.setStatus(PaypalResponseCode.getStatus(refund.getState()));
                        refundBillsMapper.updateById(refundBills);
                    } catch (Exception e) {
                        logger.error("paypal第三方通道微信H5退款查询接口调用失败"+merchantRefundNo,e);
                    }
            }
        }
        return new ResponseEntity(ResponseEntity.STATUS_OK,refundBills);
    }
}
